#!/usr/bin/python

# lametroloader.py: Provides a custom loader for the LA Metro.
# Also for the MBTA - in fact, only for the MBTA, because the LA Metro
# license prevents us from using their data.
# It grabs stop data from GTFS and route data from NextBus.

# Copyright 2011 Portland Transport

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

#   http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Authors:
# Matt Conway: main code

# The GTFS file URL is:
# 
# Note you must pass this in using the -g option, as well as passing in
# -a mbta
# There is a license requirement for this data, but no account is necessary.

import nextbusloader

class LAMetroLoader(nextbusloader.NextBusLoader):
    def loadAllStops(self):
        nbstops_unindexed = self._getStopsFromNextBus()
        nbstops = dict([(stop['stop_id'], stop) for stop in nbstops_unindexed])

        self.stops = self._getStopsFromGTFS(
            self.options.gtfsUrl,
            url=not self.options.localgtfs)

        self.agency['avl_service'] = 'NextBus'
 
        def mergeGTFSandNextBus(stop):
            # Add the NextBus route data to the GTFS data
            if nbstops.has_key(stop['stop_id']):
                nbstop = nbstops[stop['stop_id']]
                stop['routes'] = nbstop['routes']
                return stop
            else:
                # Stop has no routes
                print 'Warning: stop %s (%s) was not found in NextBus' % (stop['stop_name'], stop['stop_id'])
                return None

        self.stops = [mergeGTFSandNextBus(stop) for stop in self.stops]
        self.stops = [stop for stop in self.stops if stop != None]

if __name__ == '__main__':
    nextbusloader.main(loaderClass=LAMetroLoader)
